﻿using System.Linq;
using JetBrains.Annotations;
using Orchard;
using Orchard.ContentManagement.Drivers;
using Orchard.Environment.Features;
using RaisingStudio.Razor.Models;
using RaisingStudio.Razor.Services;
using RaisingStudio.Razor.Utilities;
using RaisingStudio.Razor.ViewModels;

namespace RaisingStudio.Razor.Drivers
{
    [UsedImplicitly]
    public class RazorContentPartDriver : ContentPartDriver<RazorContentPart>
    {
        private IRazorService razorService;
        private IOrchardServices orchardServices;
        private IFeatureManager featureManager;

        public RazorContentPartDriver(IOrchardServices orchardServices, IFeatureManager featureManager, IRazorService razorService)
        {
            this.orchardServices = orchardServices;
            this.featureManager = featureManager;
            this.razorService = razorService;
        }

        protected override DriverResult Display(RazorContentPart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_RazorContent", 
                () => shapeHelper.Parts_RazorContent(
                    Content: this.razorService.Run(part.Template, this.orchardServices, part)));
        }

        protected override DriverResult Editor(RazorContentPart part, dynamic shapeHelper)
        {
            bool useTinyMce = featureManager.GetEnabledFeatures().Any(f => f.Id == "RaisingStudio.Razor.TinyMce");
            string addMediaPath = useTinyMce ? new PathBuilder(part).AddContentType().AddContainerSlug().AddSlug().ToString() : string.Empty;
            RazorEditorViewModel razorEditorViewModel = new ViewModels.RazorEditorViewModel
            {
                Template = part.Template,
                UseTinyMce = useTinyMce,
                AddMediaPath = addMediaPath
            };
            return ContentShape("Parts_RazorContent_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/RazorContent",
                    Model: razorEditorViewModel,
                    Prefix: Prefix));
        }

        protected override DriverResult Editor(RazorContentPart part, Orchard.ContentManagement.IUpdateModel updater, dynamic shapeHelper)
        {
            RazorEditorViewModel razorEditorViewModel = new RazorEditorViewModel();
            if (updater.TryUpdateModel(razorEditorViewModel, Prefix, null, null))
            {
                part.Template = razorEditorViewModel.Template;
            }
            return Editor(part, shapeHelper);
        }
    }
}